﻿using Comkarl.Web;
using Comkarl.Web.Resources;
using Comkarl.Web.UI.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Comkarl.Calipso.Web.SampleClient.Controls
{
    public sealed class JsonClientProperty : ScriptControl
    {
        protected override string CommonID
        {
            get
            {
                return "JsonClientProperty";
            }
        }

        protected override string ControlElementCssClass
        {
            get
            {
                return "json-clientproperty";
            }
        }

        protected override void AddClientProperties()
        {
            base.AddClientProperties();

            List<object> shopItems = new List<object>();
            shopItems.Add(new { Name = "Spaguetti", Price = 2.9 });
            shopItems.Add(new { Name = "Rice", Price = 1.75 });
            shopItems.Add(new { Name = "Meat", Price = 4.99 });

            ClientProperties.Add
            (
                new ClientProperty
                {
                    Id = Guid.Parse("5e95a14a-bb56-4cc1-a07a-e74e383faeea"),
                    Name = "ShopItemList",
                    Value = JsonConvert.SerializeObject(shopItems, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None })
                }
            );
        }

        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            JavaScriptManager.RegisterInclude
            (
                "Controls//JsonClientProperty",
                "Comkarl.Calipso.Web.SampleClient.Controls.JsonClientProperty.ScriptControl.js, Comkarl.Calipso.Web.SampleClient",
                ResourceKind.Resource
            );

            JavaScriptManager.RegisterReference("Controls//JsonClientProperty");
        }
    }
}